const Menu = require('../models/menus');
const RoleMenu = require('../models/roles_menus');
const Response = require('../utils/response');
const { v4: uuidv4 } = require('uuid');

class MenuController {
    // 创建菜单
    async createMenu(ctx) {
        try {
            const menuData = ctx.request.body;
            if (menuData.level == 2) {
                if (!menuData.title || !menuData.permission || !menuData.parent_id) {
                    ctx.status = 400;
                    ctx.body = Response.error('按钮名称,权限标识和父级id为必填项', 400);
                    return;
                }
            } else {
                // 验证必填字段
                if (!menuData.title || !menuData.path) {
                    ctx.status = 400;
                    ctx.body = Response.error('菜单标题和路径为必填项', 400);
                    return;
                }
            }


            // 规范化数据
            const normalizedData = {
                id: uuidv4(), // 确保生成完整的 UUID
                title: String(menuData.title).trim(),
                path: String(menuData.path).trim(),
                parent_id: menuData.parent_id || '',
                icon: menuData.icon || '',
                level: Number(menuData.level || 0),
                permission: String(menuData.permission).trim(),
                sort: Number(menuData.sort || 0),
                hidden: Boolean(menuData.hidden)
            };

            // 创建菜单
            const menu = await Menu.create(normalizedData);
            console.log('创建的菜单:', menu); // 调试日志

            ctx.status = 201;
            ctx.body = Response.success(menu, '菜单创建成功');
        } catch (error) {
            console.error('创建菜单失败:', error);
            ctx.status = 400;
            ctx.body = Response.error(error.message);
        }
    }

    // 获取所有菜单
    async getMenus(ctx) {
        try {
            // 获取所有菜单数据并按sort排序
            const allMenus = await Menu.find().sort({ sort: 1 });

            // 先构建完整的树形结构
            const fullMenuTree = MenuController.buildMenuTree(allMenus);

            // 获取分页参数
            const { page = 1, limit = 10 } = ctx.query;
            const skip = (page - 1) * limit;

            // 对树形结构进行分页
            const paginatedTree = fullMenuTree.slice(skip, skip + Number(limit));

            // 返回分页信息和树形结构
            ctx.body = Response.success({
                total: fullMenuTree.length,
                page: Number(page),
                limit: Number(limit),
                data: paginatedTree,
                tree: fullMenuTree // 返回完整的树形结构
            });
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 获取单个菜单
    async getMenuById(ctx) {
        try {
            const menu = await Menu.findOne({ id: ctx.params.id });
            if (!menu) {
                ctx.status = 404;
                ctx.body = Response.error('菜单不存在', 404);
                return;
            }
            ctx.body = Response.success(menu);
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 更新菜单
    async updateMenu(ctx) {
        try {
            const menu = await Menu.findOneAndUpdate(
                { id: ctx.params.id },
                ctx.request.body,
                { new: true, runValidators: true }
            );
            if (!menu) {
                ctx.status = 404;
                ctx.body = Response.error('菜单不存在', 404);
                return;
            }
            ctx.body = Response.success(menu);
        } catch (error) {
            ctx.status = 400;
            ctx.body = Response.error(error.message);
        }
    }

    // 删除菜单
    async deleteMenu(ctx) {
        try {
            const menu = await Menu.findOne({ id: ctx.params.id });
            if (!menu) {
                ctx.status = 404;
                ctx.body = Response.error('菜单不存在', 404);
                return;
            }

            // 检查是否有子菜单
            const hasChildren = await Menu.findOne({ parent_id: menu.id });
            if (hasChildren) {
                ctx.status = 400;
                ctx.body = Response.error('请先删除子菜单', 400);
                return;
            }

            // 删除菜单及其角色关联
            await Menu.deleteOne({ id: menu.id });
            await RoleMenu.deleteMany({ menu_id: menu.id });

            ctx.body = Response.success(null, '删除成功');
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 改为静态方法
    static buildMenuTree(menus, parentId = '') {
        return menus
            .filter(menu => menu.parent_id === parentId)
            .map(menu => ({
                ...menu.toObject(),
                meta: {
                    title: menu.title,
                    icon: menu.icon,
                    isShow: menu.hidden
                },
                children: MenuController.buildMenuTree(menus, menu.id)
            }))
            .sort((a, b) => (a.sort || 0) - (b.sort || 0));
    }

    // 验证菜单是否存在
    async verifyMenuExists(id) {
        const menu = await Menu.findOne({ id });
        console.log('验证菜单存在:', id, !!menu);
        return !!menu;
    }
}

module.exports = new MenuController(); 